import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/JhPickerTool.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/b2cpick/b2cpickmodel.dart';
import 'package:toast/toast.dart';

class B2CPickFeedbackScreen extends StatelessWidget {
  B2CPickBean b2cPickBean;

  B2CPickFeedbackScreen({this.b2cPickBean});

  @override
  Widget build(BuildContext context) {
    return B2CPickFeedbackScreenPage(b2cPickBean: b2cPickBean);
  }
}

class B2CPickFeedbackScreenPage extends StatefulWidget {
  B2CPickBean b2cPickBean;

  B2CPickFeedbackScreenPage({this.b2cPickBean});

  @override
  _B2CPickFeedbackScreenPageState createState() => _B2CPickFeedbackScreenPageState(b2cPickBean: b2cPickBean);
}

class _B2CPickFeedbackScreenPageState extends BaseState<B2CPickFeedbackScreenPage> {
  B2CPickBean b2cPickBean;

  _B2CPickFeedbackScreenPageState({this.b2cPickBean});

  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  int index = 0, position;
  List<LPNSKU> data = new List();

  bool layoutLpn = false, layoutCodeLpn = false, layoutSku = false, layoutSkuQty = false;

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "PICK:Abnormal";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      next = "Submit";
      textEditingController.text = Utils.getStringisEmpty(b2cPickBean.location);
      _updateRadio(1);
    });
    print("b2cPickBean.location:${b2cPickBean.location}");
    if (!Utils.isEmpty(b2cPickBean.location)) {
      getLpnList(b2cPickBean.location, null);
    }
  }

  String lpn = "";

  final TextEditingController lpnEditingController = TextEditingController();
  final TextEditingController codeSkuEditingController = TextEditingController();
  final TextEditingController codeLpnEditingController = TextEditingController();
  final TextEditingController codeSkuQtyEditingController = TextEditingController();

  void _updateRadio(int value) {
    setState(() {
      hint = "";
      this.type = value;
      switch (type) {
        case 1:
          layoutLpn = true;
          layoutCodeLpn = false;
          layoutSku = true;
          layoutSkuQty = false;
          break;
        case 2:
          layoutLpn = true;
          layoutCodeLpn = false;
          layoutSku = true;
          layoutSkuQty = true;
          break;
      }
      lpnEditingController.text = "";
      codeSkuEditingController.text = "";
      codeLpnEditingController.text = "";
      codeSkuQtyEditingController.text = "";
    });
  }

  @override
  Widget getViewBinding() {
    return Container(
      margin: EdgeInsets.only(left: 15, right: 15, top: 10),
      child: Column(
        children: [
          Row(
            children: [
              Image.asset(
                'assets/images/ic_recommended.png',
                width: 15,
                height: 15,
              ),
              Text(
                " Location: ",
                style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
              ),
              Expanded(
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 35),
                  child: TextField(
                    controller: textEditingController,
                    textInputAction: TextInputAction.search,
                    onSubmitted: (String text) {
                      print('Searching for $text');
                      if (Utils.isEmpty(text)) {
                        return;
                      }
                      getLpnList(text, null);
                    },
                    // autofocus: true,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        padding: EdgeInsets.all(2.0),
                        icon: Icon(
                          Icons.qr_code_scanner,
                          size: 28,
                          color: MyAppTheme.nearlyBlue,
                        ),
                        onPressed: () {
                          // requestPermissions();
                          // Utils.scanBarcode(context);
                          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                            return ScanCode();
                          })).then((text) {
                            if (text == null) {
                              return;
                            }
                            setState(() {
                              textEditingController.text = text;
                            });
                            print(text); //拿到扫描结果
                            getLpnList(text, null);
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: MyAppTheme.nearlyBlue,
                        ),
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点之外的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点时的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      filled: true,
                      fillColor: MyAppTheme.white,
                      //隐藏下划线
                      //border: InputBorder.none,
                      hintStyle: TextStyle(color: Colors.grey),
                      contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                    ),
                    onChanged: (text) {
                      code = text;
                    },
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 1,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          _updateRadio(value);
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        "IBLPN lost",
                        style: TextStyle(color: this.type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                      onTap: () {
                        _updateRadio(1);
                      },
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.zero,
                      margin: EdgeInsets.zero,
                      height: 25.0,
                      child: Radio<int>(
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        value: 2,
                        groupValue: this.type,
                        activeColor: MyAppTheme.nearlyBlue,
                        onChanged: (value) {
                          _updateRadio(value);
                        },
                      ),
                    ),
                    GestureDetector(
                      child: Text(
                        "short of SKU",
                        style: TextStyle(color: this.type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                      onTap: () {
                        _updateRadio(2);
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
          Visibility(
              visible: layoutLpn,
              child: SizedBox(
                height: 2,
              )),
          Visibility(
            visible: layoutLpn,
            child: Row(
              children: [
                Expanded(
                    flex: 1,
                    child: Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: Text(
                            "",
                          ),
                        ),
                        Text(
                          "IBLPN LOST: ",
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                        )
                      ],
                    )),
                Expanded(
                  flex: 2,
                  child: ElevatedButton(
                    child: Row(
                      children: [
                        Expanded(
                            child: Text(
                          Utils.getStringisEmpty(lpn),
                          style: TextStyle(
                            color: MyAppTheme.darkText,
                          ),
                        )),
                        Icon(
                          Icons.keyboard_arrow_down,
                          size: 28,
                          color: MyAppTheme.nearlyBlue,
                        )
                      ],
                    ),
                    style: ButtonStyle(
                      textStyle: MaterialStateProperty.all(
                        Theme.of(context).textTheme.subtitle1,
                      ),
                      alignment: Alignment.centerLeft,
                      elevation: MaterialStateProperty.all(0),
                      backgroundColor: MaterialStateProperty.all<Color>(Colors.white),
                      shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                        RoundedRectangleBorder(
                          side: BorderSide(width: 1, color: MyAppTheme.nearlyBlue),
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                      ),
                    ),
                    onPressed: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (data == null || data.length == 0) {
                        return;
                      }
                      JhPickerTool.showStringPicker(context, data: data, clickCallBack: (int index, var str) {
                        print(index);
                        LPNSKU lpnSku = this.data[index];
                        setState(() {
                          codeSkuEditingController.text = lpnSku.sku;
                          lpn = lpnSku.ibLpn;
                        });
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
          Visibility(
              visible: layoutCodeLpn,
              child: SizedBox(
                height: 2,
              )),
          Visibility(
            visible: layoutCodeLpn,
            child: Row(
              children: [
                Expanded(
                    flex: 1,
                    child: Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: Text(
                            "",
                          ),
                        ),
                        Text(
                          "IBLPN: ",
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                        )
                      ],
                    )),
                Expanded(
                  flex: 2,
                  child: ConstrainedBox(
                    constraints: BoxConstraints(maxHeight: 35),
                    child: TextField(
                      controller: codeSkuEditingController,
                      textInputAction: TextInputAction.search,
                      onSubmitted: (String text) {
                        print('Searching for $text');
                        if (Utils.isEmpty(text)) {
                          return;
                        }
                      },
                      // autofocus: true,
                      decoration: InputDecoration(
                        suffixIcon: IconButton(
                          padding: EdgeInsets.all(2.0),
                          icon: Icon(
                            Icons.qr_code_scanner,
                            size: 28,
                            color: MyAppTheme.nearlyBlue,
                          ),
                          onPressed: () {
                            // requestPermissions();
                            // Utils.scanBarcode(context);
                            Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                              return ScanCode();
                            })).then((text) {
                              if (text == null) {
                                return;
                              }
                              setState(() {
                                textEditingController.text = text;
                              });
                              print(text); //拿到扫描结果
                            });
                          },
                        ),
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: MyAppTheme.nearlyBlue,
                          ),
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                          // 设置焦点之外的边框颜色
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                          // 设置焦点时的边框颜色
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        filled: true,
                        fillColor: MyAppTheme.white,
                        //隐藏下划线
                        //border: InputBorder.none,
                        hintStyle: TextStyle(color: Colors.grey),
                        contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                      ),
                      onChanged: (text) {
                        code = text;
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Visibility(
              visible: layoutSku,
              child: SizedBox(
                height: 2,
              )),
          Visibility(
            visible: layoutSku,
            child: Row(
              children: [
                Expanded(
                    flex: 1,
                    child: Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: Text(
                            "",
                          ),
                        ),
                        Text(
                          "SKU: ",
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                        )
                      ],
                    )),
                Expanded(
                  flex: 2,
                  child: ConstrainedBox(
                    constraints: BoxConstraints(maxHeight: 35),
                    child: TextField(
                      controller: codeLpnEditingController,
                      textInputAction: TextInputAction.search,
                      onSubmitted: (String text) {
                        print('Searching for $text');
                        if (Utils.isEmpty(text)) {
                          return;
                        }
                      },
                      // autofocus: true,
                      decoration: InputDecoration(
                        suffixIcon: IconButton(
                          padding: EdgeInsets.all(2.0),
                          icon: Icon(
                            Icons.qr_code_scanner,
                            size: 28,
                            color: MyAppTheme.nearlyBlue,
                          ),
                          onPressed: () {
                            // requestPermissions();
                            // Utils.scanBarcode(context);
                            Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                              return ScanCode();
                            })).then((text) {
                              if (text == null) {
                                return;
                              }
                              setState(() {
                                textEditingController.text = text;
                              });
                              print(text); //拿到扫描结果
                            });
                          },
                        ),
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: MyAppTheme.nearlyBlue,
                          ),
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                          // 设置焦点之外的边框颜色
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                          // 设置焦点时的边框颜色
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        filled: true,
                        fillColor: MyAppTheme.white,
                        //隐藏下划线
                        //border: InputBorder.none,
                        hintStyle: TextStyle(color: Colors.grey),
                        contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                      ),
                      onChanged: (text) {
                        code = text;
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Visibility(
              visible: layoutSkuQty,
              child: SizedBox(
                height: 2,
              )),
          Visibility(
            visible: layoutSkuQty,
            child: Row(
              children: [
                Expanded(
                    flex: 1,
                    child: Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: Text(
                            "",
                          ),
                        ),
                        Text(
                          "Updated QTY: ",
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                        )
                      ],
                    )),
                Expanded(
                  flex: 2,
                  child: ConstrainedBox(
                    constraints: BoxConstraints(maxHeight: 35),
                    child: TextField(
                      controller: codeSkuQtyEditingController,
                      keyboardType: TextInputType.number,
                      textInputAction: TextInputAction.search,
                      onSubmitted: (String text) {
                        print('Searching for $text');
                        if (Utils.isEmpty(text)) {
                          return;
                        }
                      },
                      // autofocus: true,
                      decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: MyAppTheme.nearlyBlue,
                          ),
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                          // 设置焦点之外的边框颜色
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                          // 设置焦点时的边框颜色
                          borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                        ),
                        filled: true,
                        fillColor: MyAppTheme.white,
                        //隐藏下划线
                        //border: InputBorder.none,
                        hintStyle: TextStyle(color: Colors.grey),
                        contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                      ),
                      onChanged: (text) {
                        code = text;
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    // if (Utils.isEmpty(strDate)) {
    //   Toast.show("Please select Drop Date", duration: Toast.lengthShort, gravity: Toast.bottom);
    //   return;
    // }
    if (Utils.isEmpty(lpn)) {
      Toast.show("Please select LPN", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    PickupPol3FeedbackQr putatayFeedbackQr = new PickupPol3FeedbackQr();
    putatayFeedbackQr.ibLpn = lpn;
    switch (type) {
      case 0:
        putatayFeedbackQr.abnormalType = "ibLpnLost";
        break;
      case 1:
        if (Utils.isEmpty(codeSkuEditingController.text)) {
          Toast.show("Please input Sku", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
        if (Utils.isEmpty(codeSkuQtyEditingController.text)) {
          Toast.show("Please input SkuQty", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
        if (!Utils.isEmpty(codeSkuQtyEditingController.text)) {
          Toast.show("Please input SkuQty", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
        int qty = int.parse(codeSkuQtyEditingController.text);

        putatayFeedbackQr.missingSkuQty = qty;
        putatayFeedbackQr.abnormalType = "shortOfSku";
        break;
    }
    putPutatayFeedback(putatayFeedbackQr);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      lpnEditingController.text = "";
      codeSkuEditingController.text = "";
      codeLpnEditingController.text = "";
      codeSkuQtyEditingController.text = "";
    });
  }

  void getLpnList(String location, String sku) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    Map<String, dynamic> map = new HashMap();
    map["location"] = location;
    if (!Utils.isEmpty(sku)) {
      map["sku"] = sku;
    }

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.pick_b2c_v2_abnormal_ibLpnList, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        data = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => LPNSKU.fromJson(userJson)).toList());
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void putPutatayFeedback(PickupPol3FeedbackQr putatayFeedbackQr) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context, title: "Submit...");
    } catch (e) {
      e.toString();
    }
    var json = jsonEncode(putatayFeedbackQr);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.pick_b2c_v2_abnormal_submit, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      Navigator.of(context).pop(true);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }
}
